import React from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import util from '@/utils';
import {Button, FormInstance, message, Modal, Popconfirm, Space} from 'antd';
import ProCard from '@ant-design/pro-card';
import ProForm, {ProFormGroup, ProFormSelect, ProFormText} from '@ant-design/pro-form';

import styles from '@/common/index.less';
import TreeMap from '@/components/tree-map';
import useModal from '@/hooks/modal';

const saveTableData = async (data: any) => {
   const {code} = await util.request({
      url: `/tree-adoption`,
      method: 'POST',
      data: data
   });
   code === 200 ? message.success('修改成功') : message.warn('修改失败');
};

const deleteTableData = async (id: number) => {
   const {code} = await util.request({
      url: `/tree-adoption/${id}`,
      method: 'DELETE'
   });
   if (code === 200) {
      message.success('删除成功');
   } else {
      message.warn('删除失败');
   }
};


const queryTreeInfoList = async () => {
   const {data} = await util.request({
      url: `/tree-adoption`
   });
   return data;
};


export default function TreeInfo() {

   const tabActiveKeyState = React.useState<string>('base');

   const selectedIdState = React.useState<number>();

   const formRef = React.useRef<FormInstance>();

   const modal = useModal({
      title: '请点击选择地址',
      content:<div style={{width: '100%', height: '400px'}}>
         <TreeMap
            onClick={(e: { lnglat: { lng: number; lat: number; }; }) => {
               formRef.current?.setFieldsValue({
                  lng: e.lnglat.lng,
                  lat: e.lnglat.lat
               });
            }} />
      </div>
   });

   React.useEffect(() => {
      if (tabActiveKeyState[0] === 'edit' && selectedIdState[0]) {
         // queryById(selectedIdState[0]).then((res: Article) => {
         //    formRef.current?.setFieldsValue(res);
         // });
      }
   }, [tabActiveKeyState]);

   return <PageContainer
      className={styles.pageContainer}
      tabList={[{tab: '基本信息', key: 'base'}, {tab: '信息编辑', key: 'edit'}]}
      tabActiveKey={tabActiveKeyState[0]}
      extra={[
         <Button type='primary' onClick={() => {
            selectedIdState[1](0);
            tabActiveKeyState[1]('edit');
         }}>
            添加
         </Button>
      ]}
      footer={tabActiveKeyState[0] === 'edit' ? [
         <Button type='primary' onClick={async () => {
            const form = await formRef.current?.validateFields();
            saveTableData({
               ...form
            });
         }}>发布 </Button>
      ] : []}
      onTabChange={async (e) => {
         tabActiveKeyState[1](e);
      }}>

      {
         tabActiveKeyState[0] === 'base' &&
         (<ProTable
            bordered
            columns={[
               {
                  dataIndex: 'name',
                  title: '名称',
                  width: 160
               },
               {
                  dataIndex: 'img',
                  title: '缩略图',
                  width: 120,
                  valueType: 'image'
               },
               {
                  title: '树木地址',
                  width: 260,
                  render: (text: any, record: Scenic, _: any, action: any) => {
                     return `经度：${record.lng},纬度：${record.lat}`;
                  }
               },
               {
                  dataIndex: 'isMaster',
                  title: '是否认养',
                  width: 100,
                  valueEnum: {
                     0: '未认养',
                     1: '已认养'
                  }
               },
               {
                  dataIndex: 'master',
                  title: '认养人',
                  width: 200,
                  ellipsis: true
               },
               {
                  dataIndex: 'date',
                  valueType: 'dateTime',
                  title: '创建日期',
                  width: 180
               },
               {
                  title: '操作',
                  valueType: 'option',
                  render: (text: any, record: any, _: any, action) => [
                     <a onClick={() => {
                        selectedIdState[1](record.id);
                        tabActiveKeyState[1]('edit');
                        setTimeout(() => {
                           formRef.current?.setFieldsValue(record);
                        }, 500);
                     }}
                     >
                        编辑
                     </a>,
                     <Popconfirm
                        title='确定删除吗？'
                        onConfirm={() => {
                           selectedIdState[1](record.id);
                           record.id && deleteTableData(record.id);
                           action?.reloadAndRest?.();
                        }}
                        okText='是'
                        cancelText='否'
                     >
                        <a>删除</a>
                     </Popconfirm>
                  ]
               }]}
            request={async () => {
               return Promise.resolve({
                  data: await queryTreeInfoList(),
                  success: true
               });
            }}
            rowKey='id'
            pagination={false}
            toolBarRender={false}
            search={false}
         />)
      }
      {
         tabActiveKeyState[0] === 'edit' &&
         <Space direction='vertical' className={styles.editTab}>
            <ProCard title='信息编辑' className={styles.form}>
               <ProForm
                  layout='horizontal'
                  formRef={formRef}
                  validateMessages={{
                     required: '必填项'
                  }}
                  submitter={false}
               >
                  <ProFormText name='id' hidden />
                  <ProFormGroup>
                     <ProFormText
                        width='xl'
                        rules={[{required: true}]}
                        name='name'
                        label='树木名称'
                        placeholder='请输入名称'
                     />
                  </ProFormGroup>
                  <ProFormGroup>
                     <ProFormText
                        width='xl'
                        name='img'
                        rules={[{required: true}]}
                        label='缩略图片'
                        placeholder='请输入图片地址'
                     />
                  </ProFormGroup>

                  <ProFormGroup>
                     <ProFormText
                        width='sm'
                        rules={[{required: true}]}
                        name='lng'
                        fieldProps={{
                           onClick: (event) => {
                              event.preventDefault();
                              event.stopPropagation();
                              modal.open();
                           }
                        }}
                        label='景点经度'
                        placeholder='请点击选择'
                     />
                     <ProFormText
                        width='sm'
                        fieldProps={{
                           onClick: (event) => {
                              event.preventDefault();
                              event.stopPropagation();
                              modal.open();
                           }
                        }}
                        rules={[{required: true}]}
                        name='lat'
                        label='景点纬度'
                        placeholder='请点击选择'
                     />
                  </ProFormGroup>

                  <ProFormGroup>
                     <ProFormSelect
                        rules={[{required: true}]}
                        name='isMaster'
                        width='xl'
                        options={[
                           {
                              value: 0,
                              label: '未认养'
                           },
                           {
                              value: 1,
                              label: '已认养'
                           }
                        ]}
                        label='是否认养'
                        placeholder='是否认养'
                     />
                  </ProFormGroup>
               </ProForm>
            </ProCard>
         </Space>
      }
   </PageContainer>;
}
